package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.cache.util.RedisKeys;
import cn.wolfcode.wolf2w.cache.vo.VisitorVo;
import cn.wolfcode.wolf2w.domain.Visitor;
import cn.wolfcode.wolf2w.service.IVisitorService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

//@Component //(扫描监听器初始化)
public class VisitorRedisDataInitListener implements ApplicationListener<ContextRefreshedEvent>{
    @Autowired
    private IVisitorService visitorService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("初始化star-----------------------------");

        // 查询mongodb数据库中所有游客信息
        List<Visitor> VisitorList = visitorService.list();

        for (Visitor visitor : VisitorList){

            // 需要考虑第二次初次化时会把最新的数据进行覆盖操作,还原原来的旧数据
            // 判断是否存在vo
            String key = RedisKeys.Visitor_STATIS_VO.join(visitor.getId());
            String voStr = redisTemplate.opsForValue().get(key);
            if (StringUtils.hasLength(voStr)){
                continue; // 如果存在vo信息，则跳过下面的步骤不初始化数据
            }

            // 把mongodb数据保存到redis中
            VisitorVo vo = new VisitorVo();
            BeanUtils.copyProperties(visitor,vo);
            redisTemplate.opsForValue().set(key,JSON.toJSONString(voStr));
        }
        System.out.println("初始化end-----------------------------");
    }
}
